import axios from "axios";
import { ElMessage } from "element-plus";
import { GET_TOKEN, REMOVE_TOKEN } from "@/uitls/token";
const request = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
});
request.interceptors.request.use(
  (config) => {
    const token = GET_TOKEN();
    // if (token) config.headers.Authorization = `Bearer ${token}`
    if (token) config.headers.token = token;
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (err) => {
    let msg = "",
      status = err.response.status;
    switch (status) {
      case 401:
        // token过期清空token跳转登录页
        REMOVE_TOKEN();
        msg = "token过期";
        break;
      case 403:
        // 无权访问跳转登录页并且携带url参数
        // router.replace({path:'/login'},query:{ redirect: encodeURIComponent(router.currentRoute.fullPath) })
        REMOVE_TOKEN();
        msg = "无权访问";
        break;
      case 404:
        msg = "请求地址错误";
        break;
      case 500:
        msg = "服务器出现问题";
        break;
      default:
        msg = "无网络";
    }
    ElMessage({
      type: "error",
      message: msg,
    });
    return Promise.reject(err);
  }
);
export default request;
